{% extends "hometeacher.html" %}

{% block title %}{{ obj.name }}{% endblock %}

{% block teachercontent %}
    <p>Name: {{ obj.name }}</p>
    <p>Description: {{ obj.description }}</p>
    <p>Deadline: {{ obj.deadline }}</p>
    <p>Author: {{ obj.author }}</p>

    <a class="deletelink" href="/DeleteExam/{{ obj.id }}">Delete exam</a>
    <a class="changelink" href="/EditExam/{{ obj.id }}">Edit exam</a>
    
    <p>
        <a class="addlink" id="question-add" href="#">Add Question</a>
    </p>
    <ul id="question-list">
        {% for item in questions %}
            <li id="a-{{ item.id }}">
                <p id="ques-{{ item.id }}">Question: {{ item.question }}</p>
                <p id="poin-{{ item.id }}">Points: {{ item.point }}</p>
            </li>
            <a id="b-{{ item.id }}" href="#" class="question-delete" data-id="{{ item.id }}">Delete question</a>
            <a id="c-{{ item.id }}" href="#" class="question-edit" data-id="{{ item.id }}">Edit question</a>
            <p id="d-{{ item.id }}"><a href="#" class="answer-add" data-id="{{ item.id }}">Add answer</a></p>
            <ul id="e-{{ item.id }}">
                {% for item2 in item.answers %}
                    <li id="anscont-{{ item2.id }}"><p id="ans-{{ item2.id }}">{{ item2.answer }} | correct: {{ item2.correct }}</p></li>
                    <a id="ansdelete-{{ item2.id }}" class="answer-delete" data-id="{{ item2.id }}" href="#">Delete answer</a>
                    <a id="ansedit-{{ item2.id }}" class="answer-edit" data-id="{{ item2.id }}" href="#">Edit answer</a>
                {% endfor %}
            </ul>
        {% endfor %}
    </ul>

    <div id="dialog-form" title="Add new question">
        <p class="validateTips">All form fields are required.</p>

        <form>
            <fieldset>
                <label for="question">Question</label>
                <input type="text" name="question" id="question" class="text ui-widget-content ui-corner-all" />
                <label for="points">Points</label>
                <input type="text" name="points" id="points" value="" class="text ui-widget-content ui-corner-all" />
            </fieldset>
        </form>
    </div>

    <div id="dialog-form-edit" title="Edit question">
        <p class="validateTips"></p>

        <form>
            <fieldset>
                <label for="question-edit">Question</label>
                <input type="text" name="question-edit" id="question-edit" class="text ui-widget-content ui-corner-all" />
                <label for="points-edit">Points</label>
                <input type="text" name="points-edit" id="points-edit" value="" class="text ui-widget-content ui-corner-all" />
            </fieldset>
        </form>
    </div>

    <div id="dialog-form-answer" title="Add new answer">
        <p class="validateTips">All form fields are required.</p>

        <form>
            <fieldset>
                <label for="answer">Answer</label>
                <input type="text" name="answer" id="answer" class="text ui-widget-content ui-corner-all" />
                <label for="correct">Check if answer is correct</label>
                <input type="checkbox" name="correct" id="correct" value="" class="text ui-widget-content ui-corner-all" />
            </fieldset>
        </form>
    </div>

    <div id="dialog-form-answer-edit" title="Edit answer">
        <p class="validateTips"></p>

        <form>
            <fieldset>
                <label for="answer-edit">Answer</label>
                <input type="text" name="answer-edit" id="answer-edit" class="text ui-widget-content ui-corner-all" />
                <label for="correct-edit">Check if answer is correct</label>
                <input type="checkbox" name="correct-edit" id="correct-edit" value="" class="text ui-widget-content ui-corner-all" />
            </fieldset>
        </form>
    </div>

    <script type="text/javascript">

    $(".answer-delete").live('click', function() {
        ans = confirm("Are you sure you want to delete this answer?");
        if(ans == true){
            var answerToDelete = $(this).attr("data-id");
            if(answerToDelete != '')
            {
                $.post("/DeleteAnswer", { id: answerToDelete }, function(data) {
                    if(data.length > 0){
                        data2 = JSON.parse(data);
                        $('#anscont-' + data2[0].pk).remove();
                        $('#ansdelete-' + data2[0].pk).remove();
                        $('#ansedit-' + data2[0].pk).remove();
                    }
                    else{
                        alert("Error! Could not delete question!");
                    }
                });
            }
        }
    });

        $(".question-delete").live('click', function() {
            ans = confirm("Are you sure you want to delete this question and all of its answers?");
            if(ans == true){
                var questionToDelete = $(this).attr("data-id");
                if(questionToDelete != '')
                {
                    $.post("/DeleteQuestion", { id: questionToDelete }, function(data) {
                        if(data.length > 0){
                            data2 = JSON.parse(data);
                            //alert('Reesponse from view recieved; Removing items from view for id = ' + data2[0].pk);
                            $('#a-' + data2[0].pk).remove();
                            $('#b-' + data2[0].pk).remove();
                            $('#c-' + data2[0].pk).remove();
                            $('#d-' + data2[0].pk).remove();
                            $('#e-' + data2[0].pk).remove();
                        }
                        else{
                            alert("Error! Could not delete question!");
                        }
                    });
                }
            }
        });

        $(function() {
            // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
            $( "#dialog:ui-dialog" ).dialog( "destroy" );

            var question = $( "#question" ),
                    points = $( "#points" ),
                    allFields = $( [] ).add( question ).add( points ),
                    tips = $( ".validateTips" );

            var questionedit = $( "#question-edit" ),
                    pointsedit = $( "#points-edit" ),
                    allFieldsEdit = $( [] ).add( questionedit ).add( pointsedit );
            var questionToEdit;

            var answers = $( "#answer" ),
                    correct = $( "#correct" ),
                    allFieldsAnswer = $( [] ).add( answers ).add( correct );
            var answerToAdd;

            var answersEdit = $( "#answer-edit" ),
                    correctEdit = $( "#correct-edit" ),
                    allFieldsAnswerEdit = $( [] ).add( answersEdit ).add( correctEdit );
            var answerToEdit;


            function updateTips( t ) {
                tips
                        .text( t )
                        .addClass( "ui-state-highlight" );
                setTimeout(function() {
                    tips.removeClass( "ui-state-highlight", 1500 );
                }, 500 );
            }

            function checkLength( o, n, min, max ) {
                if ( o.val().length > max || o.val().length < min ) {
                    o.addClass( "ui-state-error" );
                    updateTips( "Length of " + n + " must be between " +
                            min + " and " + max + "." );
                    return false;
                } else {
                    return true;
                }
            }

            function checkRegexp( o, regexp, n ) {
                if ( !( regexp.test( o.val() ) ) ) {
                    o.addClass( "ui-state-error" );
                    updateTips( n );
                    return false;
                } else {
                    return true;
                }
            }

            $( "#dialog-form-answer-edit" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Edit answer": function() {
                        var bValid = true;
                        allFieldsAnswerEdit.removeClass( "ui-state-error" );
                        bValid = bValid && checkLength( answersEdit, "answer-edit", 1, 100 );
                        if ( bValid ) {
                            var answerUpdated = $("#answer-edit").val();
                            var correctUpdated = $("#correct-edit").prop('checked');
                            var cor = 0;
                            if ( correctUpdated == true ) {
                                cor = 1;
                            }
                            $.post("/EditAnswerSave", { ans: answerUpdated, corr: cor, id: answerToEdit }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $('#ans-' + data2[0].pk).remove();
                                    $('#anscont-' + data2[0].pk).append("<p id='ans-"+ data2[0].pk +"'>" + data2[0].fields.answer + " | correct: " + data2[0].fields.correct + "</p>");
                                }
                                else {
                                    alert("Error! Could not edit answer!");
                                }
                            });
                            $( this ).dialog( "close" );
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    allFieldsAnswerEdit.val( "" ).removeClass( "ui-state-error" );
                }
            });

            $( "#dialog-form-answer" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Add answer": function() {
                        var bValid = true;
                        allFieldsAnswer.removeClass( "ui-state-error" );
                        bValid = bValid && checkLength( answers, "answer", 1, 100 );
                        if ( bValid ) {
                            var answer = $("#answer").val();
                            var correct = $("#correct").prop('checked');
                            var cor = 0;
                            if ( correct == true ) {
                                cor = 1;
                            }
                            $.post("/AddAnswer", { ans: answer, corr: cor, id: answerToAdd }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $("#e-" + data2[0].fields.question).append("<li id='anscont-"+ data2[0].pk +"'><p id='ans-"+ data2[0].pk +"'>" + data2[0].fields.answer +" | correct: " + data2[0].fields.correct + "</p></li>" +
                                            "<a id='ansdelete-"+ data2[0].pk + "' href='#' class='answer-delete' data-id='" + data2[0].pk + "'>Delete answer</a> " +
                                            "<a id='ansedit-"+ data2[0].pk + "' href='#' class='answer-edit' data-id='" + data2[0].pk + "'>Edit answer</a> ");
                                }
                                else {
                                    alert("Error! Could not add answer!");
                                }
                            });
                            $( this ).dialog( "close" );
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    allFieldsAnswer.val( "" ).removeClass( "ui-state-error" );
                }
            });

            $( "#dialog-form" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Add question": function() {
                        var bValid = true;
                        allFields.removeClass( "ui-state-error" );

                        bValid = bValid && checkLength( question, "question", 1, 100 );
                        bValid = bValid && checkLength( points, "points", 1, 3 );

                        //bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                        //bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
                        bValid = bValid && checkRegexp( points, /^([0-9])+$/, "Points field only allow : 0-9" );

                        if ( bValid ) {
                            var questions = $("#question").val();
                            var pointss = $("#points").val();
                            //$.get("/AddQuestion", function(data) {
                            //    alert(data);
                            //});
                            $.post("/AddQuestion", { qu: questions, pt: pointss, id: {{ obj.id }} }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $("#question-list").append("<li id='a-"+ data2[0].pk + "'>" +
                                            "<p id='ques-" + data2[0].pk + "'>Question: " + data2[0].fields.question + "</p>" +
                                            "<p id='poin-" + data2[0].pk + "'>Points: " + data2[0].fields.point + "</p></li>" +
                                            "<a id='b-" + data2[0].pk + "' href='#' class='question-delete' data-id='" + data2[0].pk + "'>Delete question</a> " +
                                            "<a id='c-" + data2[0].pk + "' href='#' class='question-edit' data-id='" + data2[0].pk + "'>Edit question</a> " +
                                            "<p id='d-" + data2[0].pk + "'><a href='#' class='answer-add' data-id='" + data2[0].pk + "'>Add answer</a></p>" +
                                            "<ul id='e-" + data2[0].pk + "'></ul>");
                                }
                                else {
                                    alert("Error! Could not add question!");
                                }
                            });
                            $( this ).dialog( "close" );
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    allFields.val( "" ).removeClass( "ui-state-error" );
                }
            });

            $( "#dialog-form-edit" ).dialog({
                autoOpen: false,
                height: 300,
                width: 350,
                modal: true,
                buttons: {
                    "Save question": function() {
                        var bValid = true;
                        allFieldsEdit.removeClass( "ui-state-error" );

                        bValid = bValid && checkLength( questionedit, "question", 1, 100 );
                        bValid = bValid && checkLength( pointsedit, "points", 1, 3 );

                        //bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                        // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                        //bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
                        bValid = bValid && checkRegexp( pointsedit, /^([0-9])+$/, "Points field only allow : 0-9" );

                        if ( bValid ) {
                            var questionUpdated = $("#question-edit").val();
                            var pointsUpdated = $("#points-edit").val();
                            $.post("/EditQuestionSave", { qu: questionUpdated, pt: pointsUpdated, id: questionToEdit }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $('#ques-' + data2[0].pk).remove();
                                    $('#poin-' + data2[0].pk).remove();
                                    $('#a-' + data2[0].pk).append( "<p id='ques-" + data2[0].pk + "'>Question: " + data2[0].fields.question + "</p>" +
                                                                   "<p id='poin-" + data2[0].pk + "'>Points: " + data2[0].fields.point + "</p>");
                                }
                                else {
                                    alert("Error! Could not edit question!");
                                }
                            });
                            $( this ).dialog( "close" );
                        }
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    allFieldsEdit.val( "" ).removeClass( "ui-state-error" );
                }
            });

            $( ".answer-edit" ).live('click', function() {
                        answerToEdit = $(this).attr("data-id");
                        if(questionToEdit != ''){
                            $.post("/EditAnswer", { id: answerToEdit }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $("#answer-edit").val(data2[0].fields.answer);
                                    $("#correct-edit").prop('checked', data2[0].fields.correct);
                                    $( "#dialog-form-answer-edit" ).dialog( "open" );
                                }
                                else{
                                    alert("Error! Could not get question for editing!");
                                }
                            });
                        }
                    });

            $( ".answer-add" ).live('click', function() {
                        answerToAdd = $(this).attr("data-id");
                        $( "#dialog-form-answer" ).dialog( "open" );
                    });

            $( "#question-add" ).live('click', function() {
                        $( "#dialog-form" ).dialog( "open" );
                    });

            $( ".question-edit" ).live('click', function() {
                        questionToEdit = $(this).attr("data-id");
                        if(questionToEdit != ''){
                            $.post("/EditQuestion", { id: questionToEdit }, function(data) {
                                if(data.length > 0){
                                    data2 = JSON.parse(data);
                                    $("#question-edit").val(data2[0].fields.question);
                                    $("#points-edit").val(data2[0].fields.point);
                                    $( "#dialog-form-edit" ).dialog( "open" );
                                }
                                else{
                                    alert("Error! Could not get question for editing!");
                                }
                            });
                        }
                    });
        });

        $(document).ajaxSend(function(event, xhr, settings) {
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            function sameOrigin(url) {
                // url could be relative or scheme relative or absolute
                var host = document.location.host; // host + port
                var protocol = document.location.protocol;
                var sr_origin = '//' + host;
                var origin = protocol + sr_origin;
                // Allow absolute or scheme relative URLs to same origin
                return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                    // or any other URL that isn't scheme relative or absolute i.e relative.
                        !(/^(\/\/|http:|https:).*/.test(url));
            }
            function safeMethod(method) {
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        });
    </script>
{% endblock %}